﻿namespace Hidistro.UI.SaleSystem.Tags
{
    using Hidistro.Core;
    using Hidistro.Entities;
    using Hidistro.Entities.Commodities;
    using Hidistro.SaleSystem.Catalog;
    using Hidistro.SaleSystem.Comments;
    using System;
    using System.Data;
    using System.Runtime.CompilerServices;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Xml;

    public class Common_New_SubjectKeyword : WebControl
    {
        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write(this.RendHtml());
        }

        public string RendHtml()
        {
            //XmlNode node = TagsHelper.FindCommentNode(this.CommentId, "keyword");
            XmlNodeList nodes = TagsHelper.GetCommentDocument().SelectNodes("//Comment[@Type='keyword']");
            StringBuilder builder = new StringBuilder();
            if (nodes != null)
            {
                DataTable table = null;
                foreach (XmlNode o in nodes)
                {
                    int categoryId = 0;
                    int result = 0;
                    int.TryParse(o.Attributes["CategoryId"].Value, out result);
                    CategoryInfo category = CategoryBrowser.GetCategory(result);
                    if (category != null)
                    {
                        categoryId = category.CategoryId;
                    }
                    DataTable hotKeywords = CommentBrowser.GetHotKeywords(categoryId, 4);
                    if ((hotKeywords != null) && (hotKeywords.Rows.Count > 0))
                    {
                        if (table == null)
                        {
                            table = hotKeywords;
                        }
                        else
                        {
                            foreach (DataRow row in hotKeywords.Rows)
                            {
                                DataRow dr = table.NewRow();
                                dr.ItemArray = row.ItemArray;
                                table.Rows.InsertAt(dr, new Random().Next(table.Rows.Count));
                            }
                        }
                    }
                }
                if (table != null)
                {
                    int i = 0;
                    foreach (DataRow row in table.Rows)
                    {
                        builder.AppendFormat("<a target=\"_blank\" href=\"{0}\">{1}</a>", Globals.GetSiteUrls().SubCategory((int)row["CategoryId"], row["RewriteName"], row["ParentRewriteName"]) + "?keywords=" + Globals.UrlEncode((string)row["Keywords"]), row["Keywords"]);
                        i++;
                        if (i == this.MaxNum) break;
                        else
                            builder.Append("|");
                    }
                }
            }
            return builder.ToString();
        }
        public int MaxNum { get; set; }
    }
}

